import React from 'react'
import menuRoute from 'routes/menuRoute'
import config from 'config'
import { connect } from 'react-redux';
import constants from 'share/constants'
import errorMessage from 'share/errorMessage';
import CustomTable from 'components/custom-table'
import { setApprove } from "actions/cache";
import {messages, deepFullCopy, dealCache, queryCurrencyPrecision} from "share/common";
import {Form, Tabs, Tag, Popover, Table, Affix, message, Input, Button, Spin, Checkbox, Modal, Row, Col} from 'antd'
const TabPane = Tabs.TabPane;
const Search = Input.Search;
import moment from 'moment'
import debounce from 'lodash.debounce'
import SearchArea from 'components/search-area'
import ApproveBar from 'components/template/approve-bar'
import approveService from 'containers/approve/approve.service'
import 'styles/approve/request/request.scss'
import checkingImg from 'images/checking.png'
import loadingImg from 'images/loading.png'
import ResizeTable from "components/resize-table";

export function getNodeNameByCode(name, formCode) {
  if (!name) return
  switch (name) {
    case '合规总监审批': return '合规办公室审批';
    case '部门主管审批': return '业务审批人审批';
    case '整单审批': return '业务审批人审批';
    case 'Tax Manager审批': return '市场税务负责人审批';
    case '项目经理审批': return '项目负责人审批';
    case '财务审批': return '财务审批人审批';
    case '资金处负责人审批': return '资金部处理';
    case 'MCCL负责人审批': return '资金部处理';
    case 'C5审批': return '业务审批人审批';
    case '工会无票审批': return '工会审批';
    case '市场人事负责人/人力资源部VP审批':
      if (formCode === 'SQ003') {
        return '市场人事负责人审批'
      } else {
        return '市场人事负责人/人力资源部VP/Officer审批'
      }
    case 'VP审批':
      if (formCode === 'SQ005') {
        return '业务审批人审批'
      } else {
        return 'GM/VP/Officer审批'
      }
    case '上级领导审批':
      if (formCode === 'SQ018') {
        return '业务审批人审批'
      } else {
        return '授权人确认'
      }
    default:
      return name
  }
}
class ApproveRequest extends React.Component {
  constructor(props) {
    super(props);
    this.entityObj = {
      1001: 'requestForms',
      1002: 'expenseForms',
      3001: 'loanBillForms',
      4001: 'othersForms'
    };
    this.entityApprovedObj = {
      1001: 'requestApprovedForms',
      1002: 'expenseApprovedForms',
      3001: 'loanBillApprovedForms',
      4001: 'othersApprovedForms'
    };
    this.state = {
      loading: false,
      passLoading: false,
      rejectLoading: false,
      subLoading: false,
      tab: this.getCurrentTab(),
      checkboxLoading: false,
      approvePendingCheckboxList: [],
      submitCheckboxList:[],
      entityType: Number(props.location.query.entityType) || 1111,//是否为仪表盘来的
      approvedCheckboxList: [],
      searchForm: [
        {type: 'input', id: 'businessCode', label: messages('approve.key63'/*单号*/)},
        {
          type: 'list',
          id: 'applicantOIDs',
          label: messages('approve.key64'/*申请人*/),
          listType: 'user_condition',
          labelKey: 'fullName',
          valueKey: 'userOID',
          listExtraParams: {roleType: 'TENANT'}
        },
        {
          type: 'list',
          id: 'departmentOIDs',
          label: messages('approve.key65'/*部门*/),
          listType: 'department',
          labelKey: 'name',
          valueKey: 'departmentOid',
          single: true
        },
        {
          type: 'items', id: 'priceRange', items: [
          {type: 'input', id: 'minAmount', label: messages('approve.key66'/*金额从*/)},
          {type: 'input', id: 'maxAmount', label: messages('approve.key67'/*金额至*/)}
        ]
        },
        {
          type: 'items', id: 'dateRange', items: [
          {type: 'date', id: 'beginDate', label: messages('approve.key68'/*日期从*/)},
          {type: 'date', id: 'endDate', label: messages('approve.key69'/*日期至*/)}
        ]
        },
        {
          type: 'list',
          id: 'companyOIDs',
          label: messages('financial-management.key588')/*公司*/,
          labelKey: 'name',
          valueKey: 'companyOID',
          listType: 'permission_company',
          listExtraParams:{enabled: true}
        },
        {
          type: 'multiple',
          id: 'nodeOIDs',
          label: messages('approve.key129')/*节点*/,
          options: [],
          getUrl: `${config.baseUrl}/api/approvals/approval/nodes/name?finished=false`,
          labelKey: 'name',
          valueKey: 'key',
          method: 'get',
          renderOption: (option) => `${option.name}`
        }
      ],
      approvePendingNum: 0,
      approvePendingSearchParams: {},
      approvedSearchParams: {},
      submitSearchParams: {},
      status: [
        {label: messages('approve.key41'/*编辑中*/), value: '10011000', state: 'processing'},
        {label: messages('approve.key46'/*已撤回*/), value: '10011001', state: 'warning'},
        {label: messages('approve.key89'/*已驳回*/), value: '10011002', state: 'error'},
        {label: messages('approve.key90'/*审核驳回*/), value: '10011003', state: 'error'},
        {label: messages('approve.key91'/*审批中*/), value: '10021000', state: 'processing'},
        {label: messages('approve.key92'/*已通过*/), value: '10031000', state: 'success'},
        {label: messages('approve.key93'/*审核通过*/), value: '1004', state: 'success'},
        {label: messages('approve.key94'/*已付款*/), value: '1005', state: 'success'},
        {label: messages('approve.key95'/*还款中*/), value: '1006', state: 'processing'},
        {label: messages('approve.key96'/*已还款*/), value: '1007', state: 'success'},
        {label: messages('approve.key97'/*付款中*/), value: '1008', state: 'processing'},
        {label: messages('approve.key98'/*已停用*/), value: '1009', state: 'default'}
      ],

      columns: [
        {
          title: messages('common.sequence'/*序号*/), dataIndex: 'index', width: 50, render: (value, record, index) =>
        (index + 1 + this.state.pageSize * this.state.page) +
        (record.approverOID && record.currentUserOID && record.approverOID !== record.currentUserOID ?
          `(${messages('approve.key99'/*代理*/)})` : '')
        },
        /*{
          title: messages('approve.key70'/!*工号*!/), dataIndex: 'employeeID', render: value =>
          value ? <Popover placement="topLeft" content={value}>{value}</Popover> : '-'
        },*/
        {
          title: messages('approve.key64'/*申请人*/), dataIndex: 'applicant', width: 85, render: value =>
          (value && value.fullName) ?
            <Popover placement="topLeft" content={value.fullName}>{value.fullName}</Popover> : '-'
        },
        {
          title: messages('approve.key71'/*提交日期*/),
          dataIndex: 'submittedDate',
          sorter: true,
          width: 100,
          render: (value, record) => {
            let result = value ? moment(value).format('YYYY-MM-DD') : moment(record.lastSubmittedDate).format('YYYY-MM-DD');
            return result;
          }
        },
        {
          title: messages('approve.key87'/*单据名称*/), dataIndex: 'formName', width: 200, render: value =>
          value ? <Popover placement="topLeft" content={value}>{value}</Popover> : '-'
        },
        {
          title: messages('approve.key114')/*节点名称*/, dataIndex: 'nodeName', width: 110, render: value =>
          value ? <Popover placement="topLeft" content={value}>{value}</Popover> : '-'
        },
        {
          title: messages('approve.key63'/*单号*/), dataIndex: 'businessCode', sorter: true, width: 160, render: value =>
          value ? <Popover placement="topLeft" content={value}>{value}</Popover> : '-'
        },
        {
          title: messages('approve.key72'/*事由*/), dataIndex: 'title', width: 200, render: value =>
          value ? <Popover placement="topLeft" content={value}>{value}</Popover> : '-'
        },
        {
          title: messages('approve.key73'/*币种*/),
          dataIndex: 'currencyCode',
          width: 60,
          render: (value, record) => ['SQ024'].includes(record.formCode) ? '-' : value
        },
        {
          title: messages('approve.key74'/*金额*/),
          dataIndex: 'amount',
          sorter: true,
          width: 75,
          align: 'right',
          render: (value, record) => !['SQ007', 'SQ017', 'SQ018', 'SQ019', 'SQ008', 'SQ024'].includes(record.formCode) ? this.filterMoney(value, queryCurrencyPrecision(record.currencyCode)) : value ? value : '-'
        },
        {
          title: messages('approve.key88'/*本币金额*/), dataIndex: 'baseCurrencyAmount', width: '8%', align: 'right', sorter: true,
          render: (value, record) => !['SQ007', 'SQ017', 'SQ018', 'SQ019', 'SQ008', 'SQ024'].includes(record.formCode) ? this.filterMoney(value, queryCurrencyPrecision(record.baseCurrencyCode)) : value ? value : '-'
        }
      ],
      submitColumns: [
        {
          title: messages('common.sequence'/*序号*/), dataIndex: 'index', width: 50, render: (value, record, index) =>
        (index + 1 + this.state.pageSize * this.state.page) +
        (record.approverOID && record.currentUserOID && record.approverOID !== record.currentUserOID ?
          `(${messages('approve.key99'/*代理*/)})` : '')
        },
        /*{
          title: messages('approve.key70'/!*工号*!/), dataIndex: 'employeeID', render: value =>
          value ? <Popover placement="topLeft" content={value}>{value}</Popover> : '-'
        },*/
        {
          title: messages('approve.key64'/*申请人*/), dataIndex: 'applicantName', width: 85, render: value =>
          value ?
            <Popover placement="topLeft" content={value}>{value}</Popover> : '-'
        },
        {
          title: messages('approve.key71'/*提交日期*/),
          dataIndex: 'submittedDate',
          sorter: true,
          width: 100,
          render: (value, record) => {
            let result = value ? moment(record.submittedDate).format('YYYY-MM-DD') : messages("components.key186" /*-*/);
            return result;
          }
        },
        {
          title: messages('approve.key87'/*单据名称*/), dataIndex: 'formName', width: 110, render: value =>
          value ? <Popover placement="topLeft" content={value}>{value}</Popover> : '-'
        },
        // {
        //   title: messages('approve.key114')/*节点名称*/, dataIndex: 'nodeName', width: 110, render: value =>
        //   value ? <Popover placement="topLeft" content={value}>{value}</Popover> : '-'
        // },
        {
          title: messages('approve.key63'/*单号*/), dataIndex: 'businessCode', sorter: true, width: 160, render: value =>
          value ? <Popover placement="topLeft" content={value}>{value}</Popover> : '-'
        },
        {
          title: messages('approve.key72'/*事由*/), dataIndex: 'title', width: 200, render: value =>
          value ? <Popover placement="topLeft" content={value}>{value}</Popover> : '-'
        },
        {
          title: messages('approve.key73'/*币种*/),
          dataIndex: 'currencyCode',
          width: 60,
          render: (value, record) => ['SQ024'].includes(record.formCode) ? '-' : value
        },
        {
          title: messages('approve.key74'/*金额*/),
          dataIndex: 'amount',
          sorter: true,
          width: 75,
          align: 'right',
          render: (value, record) => !['SQ007', 'SQ017', 'SQ018', 'SQ019', 'SQ008', 'SQ024'].includes(record.formCode) ? this.filterMoney(value, queryCurrencyPrecision(record.currencyCode)) : value ? value : '-'
        },
        {
          title: messages('approve.key88'/*本币金额*/), dataIndex: 'baseCurrencyAmount', width: 100, align: 'right', sorter: true,
          render: (value, record) => !['SQ007', 'SQ017', 'SQ018', 'SQ019', 'SQ008', 'SQ024'].includes(record.formCode) ? this.filterMoney(value, queryCurrencyPrecision(record.baseCurrencyCode)) : value ? value : '-'
        },
        {
          title: messages('common.column.status'),
          dataIndex: 'status',
          width: props.language.code === 'zh_cn' ? '8%' : '13%',
          render: (value, record) => {
            return value ? (
              <Tag
                color={constants.getTextByValue(String(value + '' + record.applicationType), 'documentStatus', 'color') ||
                constants.getTextByValue(String(value + '' + record.rejectType), 'documentStatus', 'color') ||
                constants.getTextByValue(String(value), 'documentStatus', 'color')}>{constants.getTextByValue(String(value + '' + record.applicationType), 'documentStatus') || constants.getTextByValue(String(value + '' + record.rejectType), 'documentStatus') || constants.getTextByValue(String(value), 'documentStatus')}</Tag>
            ) : (<span>--</span>)
          }
        }
      ],
      approvedColumns: [
        {
          title: messages('common.sequence'/*序号*/), dataIndex: 'index', width: 50, render: (value, record, index) =>
        (index + 1 + this.state.pageSize * this.state.page) +
        (record.approverOID && record.currentUserOID && record.approverOID !== record.currentUserOID ?
          `(${messages('approve.key99'/*代理*/)})` : '')
        },
        /*{
          title: messages('approve.key70'/!*工号*!/), dataIndex: 'employeeID', render: value =>
          value ? <Popover placement="topLeft" content={value}>{value}</Popover> : '-'
        },*/
        {
          title: messages('approve.key64'/*申请人*/), dataIndex: 'applicant', width: 85, render: value =>
          (value && value.fullName) ?
            <Popover placement="topLeft" content={value.fullName}>{value.fullName}</Popover> : '-'
        },
        {
          title: messages('approve.key71'/*提交日期*/),
          dataIndex: 'submittedDate',
          sorter: true,
          width: 100,
          render: (value, record) => {
            let result = value ? moment(value).format('YYYY-MM-DD') : moment(record.lastSubmittedDate).format('YYYY-MM-DD');
            return result;
          }
        },
        {
          title: messages('approve.key87'/*单据名称*/), dataIndex: 'formName', width: 110, render: value =>
          value ? <Popover placement="topLeft" content={value}>{value}</Popover> : '-'
        },
        {
          title: messages('approve.key63'/*单号*/), dataIndex: 'businessCode', sorter: true, width: 160, render: value =>
          value ? <Popover placement="topLeft" content={value}>{value}</Popover> : '-'
        },
        {
          title: messages('approve.key72'/*事由*/), dataIndex: 'title', width: 200, render: value =>
          value ? <Popover placement="topLeft" content={value}>{value}</Popover> : '-'
        },
        {
          title: messages('approve.key73'/*币种*/),
          dataIndex: 'currencyCode',
          width: 60,
          render: (value, record) => ['SQ024'].includes(record.formCode) ? '-' : value
        },
        {
          title: messages('approve.key74'/*金额*/),
          dataIndex: 'amount',
          sorter: true,
          width: 75,
          align: 'right',
          render: (value, record) => !['SQ007', 'SQ017', 'SQ018', 'SQ019', 'SQ008', 'SQ024'].includes(record.formCode) ? this.filterMoney(value, queryCurrencyPrecision(record.currencyCode)) : value ? value : '-'
        },
        {
          title: messages('approve.key88'/*本币金额*/), dataIndex: 'baseCurrencyAmount', width: 100, align: 'right', sorter: true,
          render: (value, record) => !['SQ007', 'SQ017', 'SQ018', 'SQ019', 'SQ008', 'SQ024'].includes(record.formCode) ? this.filterMoney(value, queryCurrencyPrecision(record.baseCurrencyCode)) : value ? value : '-'
        },
        {
          title: messages('common.column.status'),
          dataIndex: 'status',
          width: props.language.code === 'zh_cn' ? '8%' : '13%',
          render: (value, record) => {
            let type = record.entityType === 3001 ? 'documentLoanStatus' : 'documentStatus';
            return value ? (
              <Tag
                color={constants.getTextByValue(String(value + '' + record.applicationType), type, 'color') ||
                constants.getTextByValue(String(value + '' + record.rejectType), type, 'color') ||
                constants.getTextByValue(String(value), type, 'color')}>{constants.getTextByValue(String(value + '' + record.applicationType), type) || constants.getTextByValue(String(value + '' + record.rejectType), type) || constants.getTextByValue(String(value), type)}</Tag>
            ) : (<span>--</span>)
          }
        }
      ],
      sort: '',
      data: [],
      subData: [],
      expandList: [],
      page: 0,
      pageSize: 10,
      pagination: {
        total: 0,
        showSizeChanger: true
      },
      batchEnabled: false, //是否有批量审批
      allEnabled: false, //是否有全量审批
      isAll: false, //是否勾选中全量审批
      visible: false, //全量审批的弹框
      selectedRowKeys: [],
      selectedRows: [], //选中的单据OID
      selectedLine:[],
      cacheSearchData: {}, //缓存筛选的数据
      loadingApprovingForms: false, //加载待审批页的表单，只加载第一次
      loanBillForms: [],
      expenseForms: [],
      requestForms: [],
      othersForms: [],
      loadingApprovedForms: false, //加载已审批页的表单，只加载第一次
      loanBillApprovedForms: [],
      expenseApprovedForms: [],
      requestApprovedForms: [],
      othersApprovedForms: [],
      submitType: `${props.location.query.submitType}` === 'true'
    }
    this.preloadUrls(this.getCurrentTab())
    this.handleSearch = debounce(this.handleSearch, 500);
  }

  preloadUrls = (tab) => {
    if (tab === 'submitting') {
      // 待提交直接跳转到固定页面

    } else if (tab === 'approving') {
      this.approveRequestDetail = menuRoute.getRouteItem('approve-request-detail', 'key'); //申请单审批详情页
      this.approveRequestQuickView = menuRoute.getRouteItem('approve-request-quick-view', 'key'); //快速查看申请单页
      this.approveExpenseReportDetail = menuRoute.getRouteItem('approve-expense-report-detail', 'key'); //报销单审批详情页
      this.approveLoanDetail = menuRoute.getRouteItem('approve-loan-detail', 'key'); //借款单审批详情页
      this.approveOtherDetail = menuRoute.getRouteItem('approve-other-detail', 'key'); //其他单审批详情页
    } else if (tab === 'approved') {
      this.approveRequestDetail = menuRoute.getRouteItem('done-approve-request-detail', 'key'); //申请单审批详情页
      this.approveRequestQuickView = menuRoute.getRouteItem('done-approve-request-quick-view', 'key'); //快速查看申请单页
      this.approveExpenseReportDetail = menuRoute.getRouteItem('done-approve-expense-report-detail', 'key'); //报销单审批详情页
      this.approveLoanDetail = menuRoute.getRouteItem('done-approve-loan-detail', 'key'); //借款单审批详情页
      this.approveOtherDetail = menuRoute.getRouteItem('done-approve-other-detail', 'key'); //其他单审批详情页
    }

  }

  componentDidMount() {
    let {approvePendingSearchParams, approvedSearchParams, entityType, submitSearchParams, submitType} = this.state;
    approvePendingSearchParams.entityType = entityType;
    approvedSearchParams.entityType = entityType;
    submitSearchParams.entityType = entityType;
    const { profile } = this.props;
    this.setState({
      tab: submitType ? 'submitting' : this.props.location.pathname.indexOf('to-be-approve') !== -1 ? 'approving' : this.props.location.pathname.indexOf('to-be-submit') !== -1 ? 'submitting' : 'approved',
      // entityType: Number(this.props.location.query.entityType) || 1111,
      batchEnabled: profile['all.Approval.batch.Enable'],
      allEnabled: profile['approve.checkall.enable']
    }, () => {
      let initList = [
        {
          id: 'entityType',
          single: true,
          items: [{
            label: messages('approve.key120')/*单据类型*/, key: 'entityType',
            options: this.getCheckListOptions(),
            expand: false,
            checked: [this.state.entityType],
          }]
        }
      ];
      this.setState({
        approvedSearchParams,
        approvePendingSearchParams,
        submitSearchParams,
        approvePendingCheckboxList: initList,
        submitCheckboxList: initList,
        approvedCheckboxList: initList
      });
      this.getCache();
    })
  }

  componentDidUpdate(prevProps) {
    const prevPath = prevProps.route.path
    const currentPath = this.props.route.path
    if (prevPath !== currentPath) {
      this.onTabChange(this.getCurrentTab(this.props))
    }
  }

  getPathByTab(tab) {
    let path = '/main/todo/'
    if (tab === 'approving') {
      path += 'to-be-approve'
    } else if (tab === 'submitting') {
      path += 'to-be-submit'
    } else {
      path = '/main/done/done-approved'
    }
    return path
    // this.props.history.push(path)
  }

  getEntityType = (entityType) => {
    const { profile } = this.props;
    let result = entityType === 1111 ? [] : [entityType];
    if (!result.length) {
      result = [3001, 4001];
      if (!profile['er.opt.approval.disabled']) {
        result.push(1002);
      }
      if (!profile['ca.opt.approval.web.disabled']) {
        result.push(1001);
      }
    }
    return result;
  };

  getCheckListOptions = () => {
    const { profile } = this.props;
    let options = [
      {label: messages('request.key278'/*全部*/), value: 1111}
    ];
    if (!profile['er.opt.approval.disabled']) {
      options.push({label: messages('approve.key121')/*报销单*/, value: 1002});
    }
    if (!profile['ca.opt.approval.web.disabled']) {
      options.push({label: messages('approve.key122')/*申请单*/, value: 1001});
    }
    options.push({label: messages('approve.key123')/*借款单*/, value: 3001});
    options.push({label: messages('approve.key124')/*其他*/, value: 4001});
    return options;
  };

  getForms = (nextTab) => {
    const { tab: currentTab, loadingApprovingForms, loadingApprovedForms } = this.state;
    let searchTab = nextTab ? nextTab : currentTab;
    let entityArr = [1001, 1002, 3001, 4001];
    searchTab === 'approving' && !loadingApprovingForms && approveService.getDocumentTypev2({finished: false}).then(res => {
      entityArr.map(entityType => {
        this.setState({
          loadingApprovingForms: true,
          [this.entityObj[entityType]]: res.data[entityType]
        }, () => {
          if (this.state.entityType !== 1111) {
            this.getFormsOID(this.state.entityType);
          }
        });
      })
    });
    searchTab === 'approved' && !loadingApprovedForms && approveService.getDocumentTypev2({finished: true}).then(res => {
      entityArr.map(entityType => {
        this.setState({
          loadingApprovedForms: true,
          [this.entityApprovedObj[entityType]]: res.data[entityType]
        }, () => {
          if (this.state.entityType !== 1111) {
            this.getFormsOID(this.state.entityType);
          }
        });
      })
    });
  };

  //处理筛选缓存数据
  dealCache = (result) => {
    const {searchForm} = this.state;
    let defaultSearchForm = deepFullCopy(this.state.searchForm);
    if (result) {
      dealCache(searchForm, result);
      this.setState({
        tab: result.tab ? result.tab : 'approving',
        page: result.page,
        defaultSearchForm
      }, () => {
        this.getForms();
        this.search(result);
        this.props.dispatch(setApprove(null));
      })
    }
  };

  onTabChange = (tab) => {
    let { approvePendingCheckboxList, approvedCheckboxList, submitCheckboxList, entityType, searchForm } = this.state;
    this.preloadUrls(tab);
    this.setState({
      tab,
      sort: '',
      approvePendingSearchParams: {},
      approvedSearchParams: {},
      submitSearchParams: {},
      page: 0,
      pageSize: 10,
      pagination: {total: 0, showSizeChanger: true}
    }, () => {
      let initList = [
        {
          id: 'entityType',
          single: true,
          items: [{
            label: messages('approve.key120')/*单据类型*/, key: 'entityType',
            options: this.getCheckListOptions(),
            expand: false,
            checked: [1111],
          }]
        }];
      this.setState({
        approvePendingCheckboxList: initList,
        approvedCheckboxList: initList,
        submitCheckboxList: initList
      });
      if (tab === 'approved') {
        entityType = Number(this.props.location.query.entityType) || 1111;
        this.dealCache({
          tab,
          formOIDs: [],
          page: 0,
          beginDate: moment().subtract(3, 'month'),
          endDate: moment(),
          entityType,
          pageSize: 10
        });
      }
      if (tab === 'submitting') {
        entityType = Number(this.props.location.query.entityType) || 1111;
        this.dealCache({
          tab,
          formOIDs: [],
          page: 0,
          beginDate: moment().subtract(3, 'month'),
          endDate: moment(),
          entityType,
          pageSize: 10
        });
      }
      else {
        entityType = Number(this.props.location.query.entityType) || 1111;
        searchForm.map(condition => {
          if (condition.id === 'dateRange') {
            condition.items = [
              {type: 'date', id: 'beginDate', label: messages('approve.key68'/*日期从*/)},
              {type: 'date', id: 'endDate', label: messages('approve.key69'/*日期至*/)}
            ]
          }
        });
        this.setState({searchForm}, () => {
          this.dealCache({tab, page: 0, entityType});
        });
      }
      this.setState({
        entityType,
        approvedCheckboxList,
        approvePendingCheckboxList,
        submitCheckboxList
      }, () => {
        this.checkboxChange({
          entityType: Number(this.props.location.query.entityType) || 1111
        });
      })
    })
  };

  getFormsOID = (entityType) => {
    let {tab, approvePendingCheckboxList, approvedCheckboxList, submitCheckboxList} = this.state;
    let formOIDs = this.state[tab === 'approving' ? this.entityObj[entityType] : this.entityApprovedObj[entityType]];
    let options = [], newCheckboxList = [];
    let checkboxList = [];
    if(tab === 'submitting'){
      checkboxList = submitCheckboxList;
    }else{
      checkboxList = tab === 'approving' ? approvePendingCheckboxList : approvedCheckboxList;
    }
    formOIDs && Object.keys(formOIDs).map(key => {
      options.push({label: key, value: formOIDs[key].join(',')})
    });
    newCheckboxList.push(checkboxList[0]);
    newCheckboxList.push({
      id: 'formOIDs',
      items: [{label: messages('approve.key87'/*单据名称*/), key: 'formOID', options: [], checkAllOption: true}]
    })
    newCheckboxList.map(form => {
      if (form.id === 'formOIDs') {
        form.items.map(item => {
          item.key === 'formOID' && (item.options = options)
        })
      }
    });
    if(tab === 'submitting'){
      this.setState({
        ['submitCheckboxList']:newCheckboxList
      })
    }else{
      this.setState({
        [tab === 'approving' ? 'approvePendingCheckboxList' : 'approvedCheckboxList']: newCheckboxList
      }, () => {
      })
    }
  };

  checkboxChange = (res) => {
    let {tab, approvePendingCheckboxList, approvedCheckboxList, submitCheckboxList} = this.state;
    if (typeof res == 'object' && res) {
      this.setState({
         entityType: res.entityType
      }, () => {
        if (res.entityType === 1111) {
          let checkboxList = [],newCheckboxList = [];
          if(tab === 'submitting'){
            checkboxList = submitCheckboxList, newCheckboxList = [];
          }else{
            checkboxList = tab === 'approving' ? approvePendingCheckboxList : approvedCheckboxList, newCheckboxList = [];
          }
          newCheckboxList.push(checkboxList[0]);
          if(tab === 'submitting'){
            this.setState({
              ['submitCheckboxList']: newCheckboxList
            })
          }else{
            this.setState({
              [tab === 'approving' ? 'approvePendingCheckboxList' : 'approvedCheckboxList']: newCheckboxList
            })
          }
          // this.setState({
          //   [tab === 'approving' ? 'approvePendingCheckboxList' : 'approvedCheckboxList']: newCheckboxList
          // })
        } else {
          this.getFormsOID(res.entityType);
        }
      })
    }
  };

  getList = () => {
    const {page, pageSize, entityType, approvePendingSearchParams, approvePendingCheckboxList, approvedCheckboxList,submitCheckboxList,
      approvedSearchParams,submitSearchParams, sort, cacheSearchData, isAll} = this.state;
    const tab = this.getCurrentTab()
    let resultEntityType = this.getEntityType(entityType);
    cacheSearchData.page = page;
    if (sort) {
      cacheSearchData.sort = sort;
    }
    if (sort && tab === 'approved') {
      approvedSearchParams.sort = sort;
    }
    if (sort && tab === 'submitting') {
      submitSearchParams.sort = sort;
    }
    if (sort && tab === 'approving') {
      approvePendingSearchParams.sort = sort;
    }
    this.setState({loading: true});
    if(tab === 'submitting'){
      approveService.getSubmittingList(resultEntityType, page, pageSize,submitSearchParams).then(res=>{
        let data = [];
        res.data.map(item => {

          data.push(item);
        });
        data && data.map(item => {
          if (item.warningList) {
            let list = JSON.parse(item.warningList);
            if (list && list.length === 1 && list[0].externalPropertyName === 'CREDIT_SPOT_CHECK') {
              item.warningList = undefined;
            }
            if (list && list.length > 1) {
              let arr = [];
              list.map(item => {
                if (item.externalPropertyName !== 'CREDIT_SPOT_CHECK') {
                  arr.push(item)
                }
              })
              item.warningList = JSON.stringify(arr);
            }
          }
        })
        this.setState({
          pagination: {
            total: Number(res.headers['x-total-count']) || 0,
            current: page + 1,
            onChange: this.onChangePaper,
            showSizeChanger: true
          },
          loading: false,
          subData:data
        }, () => {
          this.processExpandList();
          isAll && this.handleSelectIsAll();
        })
      })
    }else{

    approveService.getApproveList(tab === 'approved', resultEntityType, page, pageSize, tab === 'approved' ? approvedSearchParams : approvePendingSearchParams).then(res => {
      let data = [];
      let nodeOIDList = [];
      res.data.map(item => {
        if (item.addSign) {
          item.nodeName = messages('approve.key112')/*自选审批*/;
        }
        if (tab !== 'approved' && item.nodeOID) {
          nodeOIDList.push(item.nodeOID);
        }
        data.push(item);
      });
      data && data.map(item => {
        if (item.warningList) {
          let list = JSON.parse(item.warningList);
          if (list && list.length === 1 && list[0].externalPropertyName === 'CREDIT_SPOT_CHECK') {
            item.warningList = undefined;
          }
          if (list && list.length > 1) {
            let arr = [];
            list.map(item => {
              if (item.externalPropertyName !== 'CREDIT_SPOT_CHECK') {
                arr.push(item)
              }
            })
            item.warningList = JSON.stringify(arr);
          }
        }
      })
      if (!(tab === 'approved')) {
        this.setState({
          approvePendingNum: Number(res.headers['x-total-count']) || 0
        })
      }
      if (nodeOIDList.length) {
        approveService.getApproveNodeName(nodeOIDList).then(resq => {
          data.map(oneData => {
            if (oneData.nodeOID) {
              resq.data.map(node => {
                if (oneData.nodeOID === node.ruleApprovalNodeOID) {
                  if (oneData.nodeAddSign) {
                    oneData.nodeName = node.name + messages('approve.key111')/*(加签)*/;
                  } else {
                    oneData.nodeName = getNodeNameByCode(node.name, oneData.formCode);
                  }
                }
              });
            }
          });
          this.setState({
            loading: false,
            data
          }, () => {
            this.processExpandList();
            isAll && this.handleSelectIsAll();
          });
        }).catch(err => {
          this.setState({
            loading: false,
            data
          }, () => {
            this.processExpandList();
            isAll && this.handleSelectIsAll();
          });
        });
      } else {
        this.setState({
          loading: false,
          data
        }, () => {
          this.processExpandList();
          isAll && this.handleSelectIsAll();
        });
      }
      this.setState({
        pagination: {
          total: Number(res.headers['x-total-count']) || 0,
          current: page + 1,
          onChange: this.onChangePaper,
          showSizeChanger: true
        }
      })
    }).catch(err => {
      errorMessage(err.response);
      this.setState({
        loading: false,
      });
    })
  }
  };

  //处理列表页标签展示
  processExpandList = () => {
    let { data } = this.state;
    let expandList = [];
    data.map(item => {
      let isExpand = false; //是否有标签
      if (item.pending) {//暂挂标签
        isExpand = true;
      }
      if (item.warningList && JSON.parse(item.warningList)) {
        let warningList = JSON.parse(item.warningList);
        warningList.map(warnItem => {
          if (warnItem.showFlag === 1) {
            isExpand = true;
          }
        });
      }
      if (isExpand) {
        item.isExpand = true;
        expandList.push(item.entityOID + item.approverOID);
      }
    });
    this.setState({data, expandList});
  };

  expandedRowRender = (record) => {
    let expandedFlag = record.isExpand;
    let warningList = record.warningList ? JSON.parse(record.warningList) : [];
    return expandedFlag ? (
        <div>
          {record.pending && <div>{messages('approve.key126')/*标签：暂挂*/}</div>}
          {warningList.map(warnItem => {
            return warnItem.showFlag === 1 ? (
              <div> {messages('approve.key127')/*标签：*/}
                {warnItem.title}
              </div>
            ) : null
          })}
        </div>
      ) : null
  };

  handleExpand = (isExpand, record) => {
    let { expandList } = this.state;
    let rowKey = record.entityOID + record.approverOID;
    isExpand ? expandList.addIfNotExist(rowKey) : expandList.delete(rowKey);
    this.setState({expandList});
  };

  search = (values) => {
    if (Number(this.props.location.query.entityType) && !values.entityType) {
      values.entityType = Number(this.props.location.query.entityType);
    }
    this.setCache({...values});
    values.beginDate && (values.beginDate = moment(values.beginDate).format('YYYY-MM-DD'));
    values.endDate && (values.endDate = moment(values.endDate).format('YYYY-MM-DD'));
    if(this.state.tab === 'submitting'){
      this.setState({
        entityType: values.entityType ? values.entityType : 1111,
        ['submitSearchParams' ]: values,
        page: values.page ? values.page : 0,
        pagination: {total: 0, showSizeChanger: true}
      }, () => {
        this.getList()
      })
    }else{
      this.setState({
        entityType: values.entityType ? values.entityType : 1111,
        [this.state.tab === 'approving' ? 'approvePendingSearchParams' : 'approvedSearchParams']: values,
        page: values.page ? values.page : 0,
        pagination: {total: 0, showSizeChanger: true}
      }, () => {
        this.getList()
      })
    }

  };

  //存储筛选数据缓存
  setCache = (result) => {
    const {tab, page} = this.state;
    result.tab = tab;
    result.page = page;
    this.setState({cacheSearchData: result})
  };

  //获取筛选数据缓存
  getCache = () => {
    let result = this.props.approve;
    let {tab, selectedRowKeys, selectedRows} = this.state;
    if (result && JSON.stringify(result) !== "{}") {
      let { approvePendingCheckboxList, approvedCheckboxList, isAll, submitCheckboxList } = result;
      if (tab === 'approving') {
        approvePendingCheckboxList.map((form, index) => {
          if (form.id === 'formOIDs') {
            approvePendingCheckboxList[index].items[0].checked = result['formOIDsLable'] || [];
          }
        });
        selectedRowKeys = result['selectedRowKeys'] || [];
        selectedRows = result['selectedRows'] || [];
      }
      else if (tab === 'submitting') {
        submitCheckboxList.map((form, index) => {
          if (form.id === 'formOIDs') {
            submitCheckboxList[index].items[0].checked = result['formOIDsLable'] || [];
          }
        });
        selectedRowKeys = result['selectedRowKeys'] || [];
        selectedRows = result['selectedRows'] || [];
      }
      else {
        approvedCheckboxList.map((form, index) => {
          if (form.id === 'formOIDs') {
            approvedCheckboxList[index].items[0].checked = result['formOIDsLable'] || [];
          }
        });
      }
      this.setState({
        isAll,
        cacheSearchData: result,
        approvePendingCheckboxList,
        submitCheckboxList,
        approvedCheckboxList,
        selectedRowKeys,
        entityType: result['entityType'],
        selectedRows
      }, () => {
        this.dealCache(result)
      })
    }
    else {
      let defaultSearchForm = deepFullCopy(this.state.searchForm);
      this.getForms();
      this.getList();
      this.setState({defaultSearchForm})
    }
  };

  onChangePaper = (page) => {
    if (page - 1 !== this.state.page) {
      this.setState({page: page - 1}, () => {
        this.setCache(this.state.cacheSearchData);
      })
    }
  };

  //详情跳转
  handleRowClick = (record) => {
    console.log("record", record)
    const tab = this.getCurrentTab()
    let { cacheSearchData, selectedRowKeys, selectedRows, approvedCheckboxList, approvePendingCheckboxList, submitCheckboxList,entityType, isAll } = this.state;
    cacheSearchData.selectedRowKeys = selectedRowKeys;
    cacheSearchData.selectedRows = selectedRows;
    cacheSearchData.approvedCheckboxList = approvedCheckboxList;
    cacheSearchData.approvePendingCheckboxList = approvePendingCheckboxList;
    cacheSearchData.submitCheckboxList=submitCheckboxList;
    cacheSearchData.entityType = entityType;
    cacheSearchData.isAll = isAll;
    this.props.dispatch(setApprove(cacheSearchData));
    let url = '';

    if (tab === 'submitting') {
      const backUrlKey = 'to-be-submit'
      console.log('[DEBUG] to-be-submit record', record)
      switch (record.entityType) {
        case 1001://申请单
          menuRoute.goForm(this, record.formCode, {
            action: 'edit',
            backUrlKey,
            params: {
              formOID: record.formOID,
              applicationOID: record.entityOID,
              pageFrom: 'my',
              id: record.id
            },
            needOpen: true
          })
          break;
        case 1002://报销单
          menuRoute.goForm(this, record.formCode, {
            action: 'detail',
            backUrlKey,
            params: {
              expenseReportOID: record.entityOID,
              pageFrom: 'my',
            },
            needOpen: true
          })
          break;
        case 3001://借款单
          url =`/main/loan-billing/my-borrow/loan-detail/${record.formOID}/${record.entityOID}/:pageFrom/:applicationOID`
          // this.context.router.push(`${url}${url.indexOf("?")>-1?'&':"?"}backUrlKey=${backUrlKey}`);
          window.open(`${url}${url.indexOf("?")>-1?'&':"?"}backUrlKey=${backUrlKey}`)
          break;
        case 4001://其他
          url = this.approveOtherDetail.url.replace(':formOID', record.formOID).replace(':entityOID', record.entityOID).replace(':backType', 'history');
          // this.context.router.push(`${url}${url.indexOf("?")>-1?'&':"?"}backUrlKey=${backUrlKey}`);
          window.open(`${url}${url.indexOf("?")>-1?'&':"?"}backUrlKey=${backUrlKey}`)
          break;
      }
    } else if (tab === 'approving')  {
      const backUrlKey = "to-be-approve"
      switch (record.entityType) {
        case 1001://申请单
          url = this.approveRequestDetail.url.replace(':formOID', record.formOID).replace(':applicationOID', record.entityOID);
          url += `?approving=true&approverOID=${record.approverOID}&nodeName=${record.nodeName}`
          // this.context.router.push(`${url}${url.indexOf("?")>-1?'&':"?"}backUrlKey=${backUrlKey}`);
          window.open(`${url}${url.indexOf("?")>-1?'&':"?"}backUrlKey=${backUrlKey}`)
          break;
        case 1002://报销单
          let url = this.approveExpenseReportDetail.url.replace(':expenseReportOID', record.entityOID);
          // this.state.tab === 'approving' && (url += `?approvePending=true&approverOID=${record.approverOID}`);
          url += `?approvePending=true&approverOID=${record.approverOID}`
          // this.context.router.push(`${url}${url.indexOf("?")>-1?'&':"?"}backUrlKey=${backUrlKey}`);
          window.open(`${url}${url.indexOf("?")>-1?'&':"?"}backUrlKey=${backUrlKey}`)
          break;
        case 3001://借款单
          url = this.approveLoanDetail.url.replace(':formOID', record.formOID).replace(':loanBillOID', record.entityOID).replace(':backType', 'history');
          url += `?approving=true&approverOID=${record.approverOID}`
          // this.context.router.push(`${url}${url.indexOf("?")>-1?'&':"?"}backUrlKey=${backUrlKey}`);
          window.open(`${url}${url.indexOf("?")>-1?'&':"?"}backUrlKey=${backUrlKey}`)
          break;
        case 4001://其他
          url = this.approveOtherDetail.url.replace(':formOID', record.formOID).replace(':entityOID', record.entityOID).replace(':backType', 'history');
          url += `?approving=true&approverOID=${record.approverOID}`
          // this.context.router.push(`${url}${url.indexOf("?")>-1?'&':"?"}backUrlKey=${backUrlKey}`);
          window.open(`${url}${url.indexOf("?")>-1?'&':"?"}backUrlKey=${backUrlKey}`)
          break;
      }
    } else if (tab === 'approved') {
      const backUrlKey = "done-approved"
      switch (record.entityType) {
        case 1001://申请单
          url = this.approveRequestDetail.url.replace(':formOID', record.formOID).replace(':applicationOID', record.entityOID);
          // this.context.router.push(`${url}${url.indexOf("?")>-1?'&':"?"}backUrlKey=${backUrlKey}&isDoneApproved=true`);
          window.open(`${url}${url.indexOf("?")>-1?'&':"?"}backUrlKey=${backUrlKey}&isDoneApproved=true`)
          break;
        case 1002://报销单
          let url = this.approveExpenseReportDetail.url.replace(':expenseReportOID', record.entityOID);
          // this.context.router.push(`${url}${url.indexOf("?")>-1?'&':"?"}backUrlKey=${backUrlKey}`);
          window.open(`${url}${url.indexOf("?")>-1?'&':"?"}backUrlKey=${backUrlKey}`)
          break;
        case 3001://借款单
          url = this.approveLoanDetail.url.replace(':formOID', record.formOID).replace(':loanBillOID', record.entityOID).replace(':backType', 'history');
          // this.context.router.push(`${url}${url.indexOf("?")>-1?'&':"?"}backUrlKey=${backUrlKey}`);
          window.open(`${url}${url.indexOf("?")>-1?'&':"?"}backUrlKey=${backUrlKey}`)
          break;
        case 4001://其他
          url = this.approveOtherDetail.url.replace(':formOID', record.formOID).replace(':entityOID', record.entityOID).replace(':backType', 'history');
          // this.context.router.push(`${url}${url.indexOf("?")>-1?'&':"?"}backUrlKey=${backUrlKey}`);
          window.open(`${url}${url.indexOf("?")>-1?'&':"?"}backUrlKey=${backUrlKey}`)
          break;
      }
    }

  };

  handleTableChange = (pagination, filters, sorter) => {
    let page = pagination.current;
    let sort = '';
    if (sorter.order) {
      if (sorter.columnKey === 'amount') {
        sort = `totalAmount,${sorter.order === 'ascend' ? 'ASC' : 'DESC'}`;
      } else {
        sort = `${sorter.columnKey},${sorter.order === 'ascend' ? 'ASC' : 'DESC'}`;
      }
    }
    this.setState({
      page: page - 1,
      sort,
      pageSize: pagination.pageSize
    }, () => {
      this.getList();
    });
  };

  handleQuickView = () => {
    let url = this.approveRequestQuickView.url;
    this.context.router.push(url)
  };

  //刷新selectedRowKeys
  refreshSelectedRowKeys = () => {
    const { selectedRows } = this.state;
    let selectedRowKeys = [];
    selectedRows.length && selectedRows.map(row => {
      let record = JSON.parse(row);
      selectedRowKeys.push(`${record.entityOID}${record.approverOID}`);
    });
    this.setState({selectedRowKeys});
  };

  //列表选择更改
  onSelectChange = (selectedRowKeys) => {
    if (selectedRowKeys.length > 20) {
      message.warning(messages('approve.key100'/*最多选择20条数据*/))
    } else {
      this.setState({selectedRowKeys})
    }
  };

  //选择一行
  //选择逻辑：每一项设置selected属性，如果为true则为选中
  onSelectRow = (record, selected) => {
    let selectedRows = deepFullCopy(this.state.selectedRows);
    let selectedLine = this.state.selectedLine;
    let item = JSON.stringify({
      approverOID: record.approverOID,
      entityOID: record.entityOID,
      entityType: record.entityType,
    });
    if (selected) {
      selectedLine.push(record)
    } else {
      selectedLine.delete(record)
    }
    selected ? selectedRows.push(item) : selectedRows.delete(item);
    selectedRows.length <= 20 && this.setState({selectedRows,selectedLine}, () => {
      this.refreshSelectedRowKeys();
    });
    
  };

  //全选
  onSelectAllRow = (selected, selectedRow, changeRows) => {
    let selectedRows = deepFullCopy(this.state.selectedRows);
    let selectedLine = this.state.selectedLine;
    if(this.state.tab === 'submitting'){
      this.state.subData.map(item => {
        let row = JSON.stringify({
          approverOID: item.approverOID,
          entityOID: item.entityOID,
          entityType: item.entityType,
        });
        selected ? !item.pending && selectedRows.addIfNotExist(row) : selectedRows.delete(row);
      });
    }else{
      this.state.data.map(item => {
        let row = JSON.stringify({
          approverOID: item.approverOID,
          entityOID: item.entityOID,
          entityType: item.entityType,
        });
        selected ? !item.pending && selectedRows.addIfNotExist(row) : selectedRows.delete(row);
      });
    }
    if(selected) {
      changeRows.map(item => {
        selectedLine.push(item)
      })
    } else {
      changeRows.map(item => {
        selectedLine.delete(item)
      })
    }
    selectedRows.length <= 20 && this.setState({selectedRows,selectedLine}, () => {
      this.refreshSelectedRowKeys();
    });
  };
  //提交操作
  handleSub = () => {
    const { isAll } = this.state;
    let entities = [],tempEntities=[];
    let temp = [];
    this.state.selectedRows.map(item => {
      entities.push(JSON.parse(item))
    });
    // entities.map(items => {
    //   temp.entityOID = items.entityOID;
    //   temp.entityType = items.entityType;
    //   tempEntities.push(temp);
    // })
    let params = {
      entities,
    };
    this.setState({['subLoading']: true});
    approveService['handleRequestSub'](params).then(res => {
      if (res.status === 200) {
        message.success(messages('approve.key109', {arg1: res.data.successNum}/*成功处理 {arg1} 笔单据*/) + ', ' +
          messages('approve.key110', {arg1: res.data.failNum}/*失败 {arg1} 笔单据*/));
        this.setState({subLoading: false});
        this.setState({
          tab: 'submitting',
          page: 0,
          pagination: {total: 0, showSizeChanger: true},
          selectedRowKeys: [],
          selectedRows: [],
          pageSize: 10
        }, () => {
          this.getList()
        })
      }
    }).catch(e => {
      this.setState({subLoading: false});
      message.error(`${messages('common.operate.filed'/*操作失败*/)}，${e.response.data.message}`)
    })
  };
  //审批操作
  handleApprove = (value, type) => {
    let valid = false;
    const selectedLines =  this.state.selectedLine;
    console.log(this.state.selectedLine)
    if(type=== "pass"){
      selectedLines.map(i=>{
        if((i.formCode=== "SQ002"||i.formCode=== "SQ004") && i.nodeName === "确认签收/遗失"){
          try{
            i.giftLineList.map(item=>{
              if(item.formType != 1){
                if(item.signingStatus == "待签收" || item.signingStatus == null ){
                  valid =true;
                  message.warning(`${i.formCode=== "SQ004"?'工会礼品卡/现金券申请单':'礼品申请单'}${i.businessCode}未确认签收/遗失，无法审批`);
                  throw Error();
                }
              }
            })
          }catch(e){
          }
        }
      })
    } else if(type=== "reject"){
      selectedLines.map(i=>{
        if((i.formCode=== "SQ002"||i.formCode=== "SQ004") && i.nodeName === "确认签收/遗失"){
          valid=true;
          message.warning(`${i.formCode=== "SQ004"?'工会礼品卡/现金券申请单':'礼品申请单'}${i.businessCode}不能驳回`);
        }
      })
    }
    if(valid){
      return;
    }
    const { isAll } = this.state;
    let entities = [];
    this.state.selectedRows.map(item => {
      entities.push(JSON.parse(item))
    });
    let params = {
      entities,
      approvalTxt: value
    };

    if (isAll) {
      this.handleApproveAll(value, type);
      return;
    }
    this.setState({[type === 'pass' ? 'passLoading' : 'rejectLoading']: true});
    approveService[type === 'pass' ? 'handleRequestApprovePass' : 'handleRequestApproveReject'](params).then(res => {
      if (res.status === 200) {
        message.success(messages('approve.key109', {arg1: res.data.successNum}/*成功处理 {arg1} 笔单据*/) + ', ' +
          messages('approve.key110', {arg1: res.data.failNum}/*失败 {arg1} 笔单据*/));
        this.setState({passLoading: false, rejectLoading: false});
        this.setState({
          tab: 'approving',
          page: 0,
          pagination: {total: 0, showSizeChanger: true},
          selectedRowKeys: [],
          selectedRows: [],
          pageSize: 10
        }, () => {
          this.getList()
        })
      }
    }).catch(e => {
      this.setState({passLoading: false, rejectLoading: false});
      message.error(`${messages('common.operate.filed'/*操作失败*/)}，${e.response.data.message}`)
    })
  };

  //关闭全量审批的提示弹框
  handleClose = () => {
    this.setState({visible: false});
  };

  //全量审批
  handleApproveAll = (value, type) => {
    const { approvePendingSearchParams, entityType } = this.state;
    let resultEntityType = this.getEntityType(entityType);
    let body = {
      "approvalTxt": value,
      "operationType": type === 'pass' ? 1001 : 1002
    };
    this.setState({[type === 'pass' ? 'passLoading' : 'rejectLoading']: true});
    approveService.handleAllApprove(resultEntityType, approvePendingSearchParams, body).then(res => {
      this.setState({passLoading: false, rejectLoading: false, visible: true});
      this.getList();
    }).catch(e => {
      this.setState({passLoading: false, rejectLoading: false});
      message.error(`${messages('common.operate.filed'/*操作失败*/)}，${e.response.data.message}`)
    });
  };

  searchClear = () => {
    this.setState({cacheSearchData: {}});
    this.setCache({});
    let { defaultSearchForm } = this.state;
    this.checkboxChange({entityType: 1111});
    this.setState({
      [this.state.tab === 'approving' ? 'approvePendingSearchParams' : 'approvedSearchParams']: {},
      page: 0,
      searchForm: deepFullCopy(defaultSearchForm),
      pagination: {total: 0, showSizeChanger: true},
      pageSize: 10
    }, () => {
      this.getList()
    })
  };


  handleSearch = (value) => {
    this.setCache({...value});
    let {tab, approvePendingSearchParams, approvedSearchParams, submitSearchParams} = this.state;
    if (tab === 'approved') {
      approvedSearchParams.businessCode = value;
    }
    if (tab === 'submitting') {
      submitSearchParams.businessCode = value;
    }
    if (tab === 'approving') {
      approvePendingSearchParams.businessCode = value;
    }

    this.setState({
      page: 0,
      pagination: {
        total: 0,
        current: 1,
        showSizeChanger: true
      },
      approvedSearchParams,
      approvePendingSearchParams,
      submitSearchParams,
      pageSize: 10
    }, () => {
      this.getList();
    })
  };

  //已审批页面 搜索条件中要去除节点, 待审批页面，搜索条件增加节点搜索
  processSearchForm = (searchForm) => {
    const { tab } = this.state;
    let nodeIndex = -1;
    searchForm.map((condition, index) => {
      if (condition.id === 'nodeOIDs') {
        nodeIndex = index;
      }
    });
    if (tab === 'approving' && nodeIndex === -1) {
      searchForm.push({
        type: 'multiple',
        id: 'nodeOIDs',
        label: messages('approve.key129')/*节点*/,
        options: [],
        getUrl: `${config.baseUrl}/api/approvals/approval/nodes/name?finished=false`,
        labelKey: 'name',
        valueKey: 'key',
        method: 'get',
        renderOption: (option) => `${option.name}`
      });
    }
    if (tab === 'approved' && nodeIndex > -1) {
      searchForm.splice(nodeIndex, 1);
    }
    if (tab === 'submitting' && nodeIndex > -1) {
      searchForm.splice(nodeIndex, 1);
    }
    return searchForm;
  };

  handleChangeIsAll = (value) => {
    this.setState({isAll: value});
    if (value) {
      this.handleSelectIsAll();
    } else {
      this.setState({selectedRows: []}, () => {
        this.refreshSelectedRowKeys();
      });
    }
  };

  //勾选了全部审批，当前页的单据都要勾选上
  handleSelectIsAll = () => {
    const { data } = this.state;
    let selectedRows = [];
    data.map(item => {
      let row = JSON.stringify({
        approverOID: item.approverOID,
        entityOID: item.entityOID,
        entityType: item.entityType,
      });
      selectedRows.push(row);
    });
    this.setState({selectedRows}, () => {
      this.refreshSelectedRowKeys();
    });
  };

  /**
   *
   * @param {*} props
   * @returns {"submitting" | "approving" | "approved"}
   */
  getCurrentTab = (props) => {
    let tab = 'none'
    const routePath = (props || this.props).route.path;
    if (routePath.indexOf('to-be-submit') > -1) {
      tab = 'submitting'
    } else if (routePath.indexOf('to-be-approve') > -1) {
      tab ='approving'
    } else if (routePath.indexOf('done-approved') > -1) {
      tab ='approved'
    }
    return tab
  }

  render() {
    const { loading, entityType, searchForm, approvePendingCheckboxList, approvedCheckboxList, submitCheckboxList,
      columns, approvedColumns,submitColumns,
      data, subData,pagination, batchEnabled, selectedRowKeys, selectedRows, passLoading, rejectLoading, approvePendingNum,
      expandList, allEnabled, isAll, visible, subLoading } = this.state;
    const tab = this.getCurrentTab()
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
      onSelect: this.onSelectRow,
      onSelectAll: this.onSelectAllRow,
      getCheckboxProps: record => ({
        disabled: isAll
      })
    };
    if (tab === 'approving') {
      approvePendingCheckboxList.map((form, index) => {
        if (form.id === 'entityType') {
          approvePendingCheckboxList[index].items[0].checked[0] = entityType || 1111
        }
      });
    }
    else if (tab === 'submitting') {
      submitCheckboxList.map((form, index) => {
        if (form.id === 'entityType') {
          submitCheckboxList[index].items[0].checked[0] = entityType || 1111
        }
      });
    }
    else {
      approvedCheckboxList.map((form, index) => {
        if (form.id === 'entityType') {
          approvedCheckboxList[index].items[0].checked[0] = entityType || 1111
        }
      });
    }
    return (
      <div className={`approve-request ${selectedRows.length && tab === 'approving' ? 'bottom-100' : ''}`}>
        <div style={{display: 'none'}}>
          <Tabs type="card" activeKey={tab} onChange={this.onTabChange}>
            <TabPane tab={messages('approve.key139'/*待提交*/)} key='submitting' disabled={loading}/>
            <TabPane tab={`${messages('approve.key101'/*待处理*/)}`} key='approving' disabled={loading}/>
            {/* 已处理 */}
            <TabPane tab={messages('approve.key102')} key='approved' disabled={loading}/>
          </Tabs>
        </div>
        {tab === 'approving' &&
        <SearchArea
          searchForm={this.processSearchForm(searchForm)}
          checkboxListForm={approvePendingCheckboxList}
          isReturnLabel
          checkboxChange={this.checkboxChange}
          submitHandle={this.search}
          clearHandle={this.searchClear}
        />}
        {tab === 'approved' &&
        <SearchArea
          searchForm={this.processSearchForm(searchForm)}
          checkboxListForm={approvedCheckboxList}
          isReturnLabel
          checkboxChange={this.checkboxChange}
          submitHandle={this.search}
          clearHandle={this.searchClear}
        />}
        {tab === 'submitting' &&
        <SearchArea
          searchForm={this.processSearchForm(searchForm)}
          checkboxListForm={submitCheckboxList}
          isReturnLabel
          checkboxChange={this.checkboxChange}
          submitHandle={this.search}
          clearHandle={this.searchClear}
        />}
        <div className="table-header" style={{ marginBottom: 22 }}>
          <div className="table-header-title">
            {messages('common.total', {total: pagination.total}/*共搜索到 {total} 条数据*/)}
            {tab === 'approving' && batchEnabled && ` / ${messages('common.total.selected', {total: isAll ? pagination.total : selectedRows.length})/*已选 {total} 条*/}`}
          </div>
          <div className="table-header-buttons">
            {tab === 'approving' && !window.ISIE9 && false && <Button type="primary" onClick={this.handleQuickView}
                                            ref="approveQuickView">{messages('approve.key103'/*快速查看*/)}</Button>}
            {tab === 'approving' && batchEnabled && allEnabled && (
              <Checkbox style={{marginLeft: '20px'}} checked={isAll} onChange={(e) => this.handleChangeIsAll(e.target.checked)}>
                {messages('approve.key130')/*全选全部单据*/}
              </Checkbox>
            )}

            {tab === 'submitting' && batchEnabled && allEnabled && (
              <Checkbox style={{marginLeft: '20px'}} checked={isAll} onChange={(e) => this.handleChangeIsAll(e.target.checked)}>
                {messages('approve.key130')/*全选全部单据*/}
              </Checkbox>
            )}
            <Search
              className="input-search"
              style={{paddingRight: 0}}
              maxLength={100}
              placeholder={messages('approve.key119')/*请输入单号*/}
              onChange={(e) => this.handleSearch(e.target.value)}
            />
          </div>
        </div>
        {tab === 'approving' &&
        <ResizeTable
          rowKey={record => record.entityOID + record.approverOID}
          size="middle"
          loading={loading}
          rowSelection={tab === 'approving' && batchEnabled ? rowSelection : null}
          pagination={pagination}
          columns={columns}
          rowClassName={record => record.isExpand ? '' : 'row-expand-display-none'}
          expandedRowRender={record => this.expandedRowRender(record)}
          expandedRowKeys={expandList}
          onExpand={this.handleExpand}
          onRow={record => ({onClick: () => this.handleRowClick(record)})}
          onChange={this.handleTableChange}
          bordered
          dataSource={data}
        />
        }
        {tab === 'approved' &&
        <ResizeTable
          rowKey={record => record.entityOID + record.approverOID}
          size="middle"
          loading={loading}
          pagination={pagination}
          columns={approvedColumns}
          rowClassName={record => record.isExpand ? '' : 'row-expand-display-none'}
          expandedRowRender={record => this.expandedRowRender(record)}
          expandedRowKeys={expandList}
          onExpand={this.handleExpand}
          onRow={record => ({onClick: () => this.handleRowClick(record)})}
          onChange={this.handleTableChange}
          bordered
          dataSource={data}
        />
        }
        {tab === 'submitting' &&
        <ResizeTable
          rowKey={record => record.entityOID + record.approverOID}
          size="middle"
          loading={loading}
          rowSelection={tab === 'submitting' && batchEnabled ? false : null}
          pagination={pagination}
          columns={submitColumns}
          rowClassName={record => record.isExpand ? '' : 'row-expand-display-none'}
          expandedRowRender={record => this.expandedRowRender(record)}
          expandedRowKeys={expandList}
          onExpand={this.handleExpand}
          onRow={record => ({onClick: () => this.handleRowClick(record)})}
          onChange={this.handleTableChange}
          bordered
          dataSource={subData}
        />
        }
        <Affix
          offsetBottom={0}
          className={`bottom-bar-approve ${selectedRows.length && tab === 'approving' ? 'show' : 'hide'}`}
        >
          <ApproveBar
            passLoading={passLoading}
            rejectLoading={rejectLoading}
            batchNumber={selectedRows.length}
            allLoading={passLoading || rejectLoading}
            handleApprovePass={value => this.handleApprove(value, 'pass')}
            handleApproveReject={value => this.handleApprove(value, 'reject')}
          />
        </Affix>
        <Affix
          offsetBottom={0}
          className={`bottom-bar-approve ${selectedRows.length && tab === 'submitting' ? 'show' : 'hide'}`}
        >
          <ApproveBar
                buttons={[]}
                customButtons={true ? [{
                  text: messages('approve-management.key1')/*提交*/,
                  onClick: this.handleSub,
                  type: 'primary',
                  loading: subLoading
                }] : []}
                jobId="submitting"
                batchNumber={selectedRows.length}
                 />
        </Affix>
        <Modal
          title={messages('approve.key91')/*审批中*/}
          visible={visible}
          onCancel={this.handleClose}
          maskClosable={false}
          footer={[
            <Button key="sure" type="primary" onClick={this.handleClose}>{messages('common.ok')/*确定*/}</Button>
          ]}
        >
          <Row type="flex" gutter={16} align="middle" className="approve-all-modal">
            <Col span={8} style={{textAlign: 'right'}}>
              <img src={checkingImg} className="img-inner"/>
              <img src={loadingImg} className="img-out rotation"/>
            </Col>
            <Col span={16}>
              <div>{messages('approve.key131')/*批量审批中......*/}</div>
              <div>{messages('approve.key132')/*单据已转入后台处理，您可以离开页面，审批失败的单据会重新显示在待审批列表。*/}</div>
            </Col>
          </Row>
        </Modal>
      </div>
    )
  }
}

ApproveRequest.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    profile: state.login.profile,
    language: state.main.language,
    approve: state.cache.approve,
    loginUser: state.login.loginUser,
    loginCompany: state.login.loginCompany
  }
}

const wrappedApproveRequest = Form.create()(ApproveRequest);

export default connect(mapStateToProps)(wrappedApproveRequest)
